<template>
    <div class="con_store_main">
        <!--新增窗口-->
        <el-dialog :rules="rules" title="新增活动" :visible.sync="addBox" width="50%" :close-on-click-modal="true" center>
            <div>
                <el-form>
                    <el-form-item label="活动名称">
                        <el-input maxlength="12" show-word-limit v-model="addForm.activityName"
                            placeholder="输入活动名称"></el-input>
                    </el-form-item>
                    <el-form-item label="活动类型">
                        <el-select v-model="addForm.activityType" placeholder="选择活动类型">
                            <el-option v-for="item in activityType" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="currentActivityType !== '满减活动'" label="折扣率（单位%）">
                        <el-input maxlength="2" show-word-limit v-model="addForm.discountRate"
                            placeholder="输入活动折扣率"></el-input>
                    </el-form-item>
                    <el-form-item v-if="currentActivityType !== '折扣活动'" label="满减需达额度">
                        <el-input v-model="addForm.fullAmount" placeholder="输入满减需达额度"></el-input>
                    </el-form-item>
                    <el-form-item v-if="currentActivityType !== '折扣活动'" label="满减可减额度">
                        <el-input v-model="addForm.reduceAmount" placeholder="输入满减可减额度"></el-input>
                    </el-form-item>
                    <div>
                        <el-button @click="confirmAdd">確認添加</el-button>
                    </div>
                </el-form>
            </div>
        </el-dialog>
        <!--编辑窗口-->
        <el-dialog :rules="rules" title="修改活动信息" :visible.sync="updateBox" width="50%" :close-on-click-modal="true"
            center>
            <div>
                <el-form>
                    <el-form-item label="活动名称">
                        <el-input maxlength="12" show-word-limit v-model="updateForm.activityName"
                            placeholder="输入活动名称"></el-input>
                    </el-form-item>
                    <el-form-item label="活动类型">
                        <el-select v-model="updateForm.activityType" placeholder="选择活动类型">
                            <el-option v-for="item in activityType" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="updateCurrentActivityType !== '满减活动'" label="折扣率（单位%）">
                        <el-input maxlength="2" show-word-limit v-model="updateForm.discountRate"
                            placeholder="输入活动折扣率"></el-input>
                    </el-form-item>
                    <el-form-item v-if="updateCurrentActivityType !== '折扣活动'" label="满减需达额度">
                        <el-input v-model="updateForm.fullAmount" placeholder="输入满减需达额度"></el-input>
                    </el-form-item>
                    <el-form-item v-if="updateCurrentActivityType !== '折扣活动'" label="满减可减额度">
                        <el-input v-model="updateForm.reduceAmount" placeholder="输入满减可减额度"></el-input>
                    </el-form-item>
                    <div>
                        <el-button @click="confirmUpdate">確認修改</el-button>
                    </div>
                </el-form>
            </div>

        </el-dialog>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="活动名称">
                <el-input maxlength="12" show-word-limit v-model="formInline.activityName"
                    placeholder="输入活动名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button @click="findData" type="primary" icon="el-icon-search">搜索</el-button>
            </el-form-item>
            <el-form-item>
                <el-button @click="addActivity" type="primary" icon="el-icon-plus">新增</el-button>
            </el-form-item>
        </el-form>
        <el-table class="table" :data="tableData" style="width: 100%" v-loading="loading"
            :default-sort="{ prop: 'index', order: 'descending' }">
            <el-table-column type="index" label="序号" sortable width="80">
            </el-table-column>
            <el-table-column prop="activityName" label="活动名称" width="130">
            </el-table-column>
            <el-table-column prop="activityType" label="活动类型" width="120">
            </el-table-column>
            <el-table-column prop="discountRate" label="折扣率" width="75">
                <template slot-scope="scope">
                    <span v-if="scope.row.discountRate">{{ scope.row.discountRate }}</span>
                    <span v-else>暂无</span>
                </template>
            </el-table-column>
            <el-table-column prop="fullAmount" label="满减额度" width="100">
                <template slot-scope="scope">
                    <span v-if="scope.row.fullAmount != 0">{{ scope.row.fullAmount }}</span>
                    <span v-else>暂无</span>
                </template>
            </el-table-column>
            <el-table-column prop="reduceAmount" label="满减金额" width="100">
                <template slot-scope="scope">
                    <span v-if="scope.row.reduceAmount != 0">{{ scope.row.reduceAmount }}</span>
                    <span v-else>暂无</span>
                </template>
            </el-table-column>
            <el-table-column prop="startTime" label="开始时间" width="100">
                <template slot-scope="scope">
                    <span v-if="scope.row.startTime">{{ scope.row.startTime }}</span>
                    <span v-else>暂无</span>
                </template>
            </el-table-column>
            <el-table-column prop="endTime" label="结束时间" width="100">
                <template slot-scope="scope">
                    <span v-if="scope.row.endTime">{{ scope.row.endTime }}</span>
                    <span v-else>暂无</span>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态 ">
            </el-table-column>
            <el-table-column label="操作" width="100">
                <template slot-scope="scope">
                    <div
                        style="display: grid; grid-template-columns: repeat(2, 1fr); grid-template-rows: repeat(2, auto); gap: 5px;">
                        <el-button type="text" size="small" @click="editActivity(scope.row)">编辑</el-button>
                        <el-button type="text" size="small" @click="deleteActivity(scope.row)">删除</el-button>
                        <el-button type="text" size="small" @click="editActivityStart(scope.row)">开始</el-button>
                        <el-button type="text" size="small" @click="editActivityEnd(scope.row)">结束</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination style="margin: auto; margin-top: 8px" :hide-on-single-page="value"
            :current-page.sync="currentPage" :page-size="6" :pager-count="11" layout="prev, pager, next"
            :total="this.total" @current-change="handleSizeChange">
        </el-pagination>
    </div>
</template>
<script>
import { request } from "@/network/request/request";
export default {
    mounted() {
        this.findData();
    },
    data() {
        return {
            rules: {
                activityName: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                    { min: 1, max: 12, message: '长度在 1 到 12 个字符', trigger: 'blur' }
                ],
                discountRate: [
                    { required: this.currentActivityType === '折扣活动', message: '请输入折扣率', trigger: 'blur' },
                    { min: 1, max: 2, message: '长度在 1 到 2 个字符', trigger: 'blur' }
                ],
                fullAmount: [
                    { required: this.currentActivityType === '满减活动', message: '输入满减额度请', trigger: 'change' }
                ],
                reduceAmount: [
                    { required: this.currentActivityType === '满减活动', message: '请输入满减可减额度', trigger: 'blur' },
                ],

            },
            addForm: {
                storeId: 0,
                activityName: '',
                activityType: '满减活动',
                discountRate: '',
                fullAmount: '',
                reduceAmount: '',
            },
            updateForm: {
                activityId: 0,
                storeId: 0,
                activityName: '',
                activityType: '',
                discountRate: '',
                fullAmount: '',
                reduceAmount: '',
                status: '',
            },
            activityType: [{ value: '折扣活动', label: '折扣活动' }, { value: '满减活动', label: '满减活动' }],
            formInline: { activityName: '' },
            updateBox: false,
            addBox: false,
            currentPage: 1, // 当前页码
            pageSize: 6, // 每页显示的记录数
            total: 0, // 总数目，默认设置为 0
            loading: false,
            value: false,
            tableData: [],
            currentActivityType: '满减活动',// 新增，用于记录当前选择的活动类型
            updateCurrentActivityType: '',// 更新，用于记录当前选择的活动类型
        };
    },
    watch: {
        'addForm.activityType'(newValue) {
            this.currentActivityType = newValue;
        },
        'updateForm.activityType'(newValue) {
            this.updateCurrentActivityType = newValue;
        }
    },
    methods: {
        time() {
            this.loading = true;
            setTimeout(() => {
                this.loading = false;
            }, 600);
        },
        handleSizeChange() {
            this.findData();
        },
        deleteAlert(row) {
            this.$confirm('此操作将永久删除该活动, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteRequest(row);
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        editActivity(row) {
            this.updateBox = true;
            this.updateCurrentActivityType = row.activityType;
            this.updateForm.storeId = row.storeId;
            this.updateForm.activityId = row.activityId;
            this.updateForm.activityName = row.activityName;
            this.updateForm.activityType = row.activityType;
            this.updateForm.discountRate = row.discountRate;
            this.updateForm.fullAmount = row.fullAmount;
            this.updateForm.reduceAmount = row.reduceAmount;
            this.updateForm.status = row.status;
        },
        async editActivityStart(row) {
            let status = '';
            if (row.status === "活动未开始") {
                status = '活动进行';
            } else if (row.status === "活动结束") {
                this.$message.error("活动已结束，无法开始")
                return;
            } else if (row.status === "活动进行") {
                this.$message.error("活动已开始")
                return;
            }
            const config = {
                url: 'api/user/activity',
                method: "put",
                data: {
                    storeId: localStorage.getItem("storeId"),
                    activityId: row.activityId,
                    status: status
                }
            }
            const res = await request(config);
            if (res.data.code === 1) {
                this.$message.success("修改成功");
                this.findData();
                this.updateBox = false;
            }
        },
        async editActivityEnd(row) {
            const storeId = localStorage.getItem("storeId");
            if (storeId == 0) {
                this.$message.error("无店铺数据！");
                return;
            }
            let status = '';
            if (row.status === "活动进行") {
                status = '活动结束';
            } else if (row.status === "活动结束") {
                this.$message.error("活动已结束")
                return;
            } else if (row.status === "活动未开始") {
                this.$message.error("活动未开始无法结束")
                return;
            }
            const config = {
                url: 'api/user/activity',
                method: "put",
                data: {
                    storeId: localStorage.getItem("storeId"),
                    activityId: row.activityId,
                    status: status
                }
            }
            const res = await request(config);
            if (res.data.code === 1) {
                this.$message.success("修改成功");
                this.findData();
                this.updateBox = false;
            }
        },
        addActivity() {
            this.addBox = true;
        },
        deleteActivity(row) {
            this.deleteAlert(row);
        },
        async confirmUpdate() {
            const storeId = localStorage.getItem("storeId");
            if (storeId == 0) {
                this.$message.error("无店铺数据！");
                return;
            }
            const config = {
                url: 'api/user/activity',
                method: "put",
                data: {
                    storeId: localStorage.getItem("storeId"),
                    activityId: this.updateForm.activityId,
                    activityName: this.updateForm.activityName,
                    activityType: this.updateForm.activityType,
                    discountRate: this.updateForm.discountRate,
                    fullAmount: this.updateForm.fullAmount,
                    reduceAmount: this.updateForm.reduceAmount,
                    status: this.updateForm.status,
                }
            }
            const res = await request(config);
            if (res.data.code === 1) {
                this.$message.success("修改成功");
                this.findData();
                this.updateBox = false;
            }
        },
        async findData() {
            this.time();
            const storeId = localStorage.getItem("storeId");
            if (storeId == 0) {
                this.$message.error("无店铺数据！");
                return;
            }
            const params = {
                activityName: this.formInline.activityName,
                currentPage: this.currentPage /* 当前页码 */,
                pageSize: this.pageSize /* 页码大小 */,
                storeId: localStorage.getItem("storeId"),
            };
            const config = {
                url: "api/user/activity",
                method: "get",
                params: params,
            };
            const res = await request(config);
            if (res.data.code === 1) {
                this.total = res.data.data.total; /* 得到数据的总数 */
                this.tableData = res.data.data.pageList; /* 得到数据 */
            }
        },
        async deleteRequest(row) {
            const storeId = localStorage.getItem("storeId");
            if (storeId == 0) {
                this.$message.error("无店铺数据！");
                return;
            }
            console.log('Status before check:', row.status);
            if (row.status === '活动进行') {
                this.$message.error("活动未开始和结束才可以删除！")
                return;
            } else {
                // row.status !== '活动结束' || row.status !== '活动未开始'
            }
            let activityId = row.activityId;
            const config = {
                url: `api/user/activity/${activityId}`,/* 通过路径参数 路径参数 */
                method: "delete",
            }
            const res = await request(config);
            if (res.data.code === 1) {
                this.$message({
                    type: 'success',
                    message: '删除成功'
                });
                this.findData();
            } else {
                this.$message({
                    type: 'error',
                    message: '删除失败'
                });
            }

        },
        async confirmAdd() {
            const storeId = localStorage.getItem("storeId");
            if (storeId == 0) {
                this.$message.error("无店铺数据！");
                return;
            }
            const config = {
                url: "api/user/activity",
                method: "post",
                data: {
                    storeId: localStorage.getItem("storeId"),
                    activityName: this.addForm.activityName,
                    activityType: this.addForm.activityType,
                    discountRate: this.addForm.discountRate,
                    fullAmount: this.addForm.fullAmount,
                    reduceAmount: this.addForm.reduceAmount,
                }
            }
            const res = await request(config);
            if (res.data.code == 1) {
                this.$message.success("添加成功");
                this.addBox = false;
            }
            this.findData();
        },

    },
};
</script>
<style scoped>
.con_store_main {
    height: 498px;
    display: flex;
    flex-direction: column;
    align-content: center;
    justify-content: center;
}
</style>